import 'dart:async';

import 'package:enjoy_life/utils/CheckAuth.dart';
import 'package:enjoy_life/utils/EventsBus.dart';
import 'package:enjoy_life/utils/NetworkService.dart';
import 'package:enjoy_life/utils/Toast.dart';
import 'package:flutter/material.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  // 当前倒计时
  int _countdown = 60;
  // 总倒计时
  final totalCountDown = 60;
  // 是否正在倒计时
  bool _isCountingdown = false;
  // 计时器
  Timer? _timer;

  // 开启倒计时
  void _startCountdown() {
    // 正在倒计时
    // if (_isCountingdown) return;

    // 提示用户
    // CustomToast.success('发送验证码成功');
    // 开启倒计时
    _isCountingdown = true;
    // 创建计时器
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdown > 1) {
        setState(() {
          _countdown--;
        });
      } else {
        // 倒计时结束
        _isCountingdown = false;
        // 取消计时器
        _timer?.cancel();
        // 重置倒计时
        setState(() {
          _countdown = totalCountDown;
        });
      }
    });
  }

  // 手机号输入框
  final TextEditingController _phoneController = TextEditingController();
  // 验证码输入框
  final TextEditingController _codeController = TextEditingController();

  // 获取验证码
  void _getCode() async {
    // 正在倒计时
    if (_isCountingdown) return;
    // 获取验证码
    final phone = _phoneController.text;
    // 验证手机号
    if (phone.isEmpty) {
      CustomToast.error('手机号不能为空');
      return;
    }

    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phone)) {
      CustomToast.error('手机号格式不正确');
      return;
    }

    // 发送验证码
    var res = await http.get('/code', params: {'mobile': phone});
    CustomToast.success('发送验证码成功');
    // 回显输入框
    setState(() {
      _codeController.text = res['data']['code'];
    });
    // 开启倒计时
    _startCountdown();
  }

  // 登录
  Future<void> login() async {
    // 获取验证码
    final phone = _phoneController.text;
    final code = _codeController.text;
    // 验证手机号
    if (phone.isEmpty) {
      CustomToast.error('手机号不能为空');
      return;
    }

    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(phone)) {
      CustomToast.error('手机号格式不正确');
      return;
    }

    // 验证手机号
    if (code.isEmpty) {
      CustomToast.error('验证码不能为空');
      return;
    }

    var res = await http.post('/login', data: {'mobile': phone, 'code': code});

    // 提示用户
    if (res['code'] != 10000) return CustomToast.error('登录失败');
    CustomToast.success('登录成功');

    // 清除定时器
    _timer?.cancel();

    // 登录成功
    // 保存token
    await CheckAuth().saveToken(res['data']['token']);

    eventBus.fire(LoginEvent());
    // ignore: use_build_context_synchronously
    Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          title: const Text('登录'),
          backgroundColor: Colors.transparent,
          centerTitle: true,
        ),
        body: Container(
            padding: const EdgeInsets.all(20),
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              const Row(
                children: [
                  Text('登录',
                      style:
                          TextStyle(fontSize: 25, fontWeight: FontWeight.bold))
                ],
              ),
              const SizedBox(height: 10),
              const Row(
                children: [
                  Text('加入享+, 让生活更轻松', style: TextStyle(fontSize: 15))
                ],
              ),
              const SizedBox(height: 30),
              Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Expanded(
                    child: TextField(
                      keyboardType: TextInputType.phone,
                      controller: _phoneController,
                      decoration: InputDecoration(
                        labelText: '手机号',
                        hintText: '请输入手机号',
                      ),
                    ),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.white,
                      shadowColor: Colors.transparent,
                      foregroundColor: const Color.fromARGB(255, 85, 145, 175),
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _getCode();
                    },
                    child: _isCountingdown
                        ? Text(
                            '$_countdown s后重新获取',
                            style: TextStyle(color: Colors.grey),
                          )
                        : const Text('获取验证码'),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              TextField(
                controller: _codeController,
                maxLength: 6,
                decoration: const InputDecoration(
                  labelText: '验证码',
                  hintText: '请输入6位验证码',
                ),
              ),
              const SizedBox(height: 8),
              const Row(children: [
                Text('未注册手机号经验证后将自动登录',
                    style: TextStyle(fontSize: 12, color: Colors.grey)),
              ]),
              const SizedBox(height: 50),
              Row(children: [
                Expanded(
                    child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: const Color.fromARGB(255, 85, 145, 175),
                    minimumSize: const Size(100, 50),
                  ),
                  onPressed: () {
                    login();
                  },
                  child: const Text('登录',
                      style: TextStyle(color: Colors.white, fontSize: 20)),
                ))
              ])
            ])));
  }
}
